/*
 * CMSHomeFactory.java
 *
 * Created on 13 November 2005, 18:35
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */

package web.util;

import java.util.Hashtable;
import javax.ejb.EJBHome;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

/**
 *
 * @author phil & chris
 */
public class HomeFactory {
    
    private static HomeFactory singleton;
    private Hashtable delegateHomes;
    private Context context;
    
    
    private HomeFactory() throws NamingException {
        this.delegateHomes = new Hashtable();
        this.context = new InitialContext();
    }
    
    
    public static synchronized HomeFactory getInstance() throws NamingException {
        if (null == singleton) {
            HomeFactory.singleton = new HomeFactory();
        }
        return HomeFactory.singleton;
    }
    
    /** Returns the Session Facade's RemoteHome, from which it can be created
     * @param jndiName the jndiName od the Session facade (i use ENC lookup)
     * @param homeClass the Session Facade's Class objects
     */
    public synchronized EJBHome lookupHome(String jndiName, Class homeClass) throws NamingException, Exception {
        EJBHome home = (EJBHome)this.delegateHomes.get(homeClass);
        if (null == home) {
	    try {
                Object o1 = this.context.lookup(jndiName);
                String myClass = o1.getClass().toString();
                
                if (o1.getClass().equals(this.context)) {
                    o1 = ((InitialContext)o1).lookup(jndiName);
                }
                Object o2 = PortableRemoteObject.narrow(o1, homeClass);
                home = (EJBHome) o2;
		this.delegateHomes.put(homeClass, home); //store in Hashtable, for repeated access.
	    }
	    catch (Exception e) {
		throw new Exception(e.getMessage() + "jndi= " + jndiName + " class= " + homeClass.toString() + "cannot be found");
	    }
        }
        return home;
    }
    
}
